<?php
namespace App\Job\Prize;

use App\Query\UserQuery;
use App\Repository\UserRepository;

// 分红
class Red
{
    public $money;
    
    public $all;
    
    public $config;
    
    public function __construct($money, $all, $config)
    {
        $this->all = $all;
        $this->money = $money;
        $this->config = json_decode($config['red'], true);;
    }
    
    // 运行
    public function run($content)
    {
        // 循环配置
        foreach($this->config as $config)
        {
            // 从关系链查找用户
            $users = UserQuery::moneyUserMinUser(
                UserQuery::in(UserQuery::model(), $this->all),
                $config['money_user_min'],
                $config['money_user']
            )->get();
            
            // 发放奖励
            $this->prize($users, $config['bi'], $content);
        }
    }
    
    // 发放奖励
    public function prize($users, $bi, $content)
    {
        // 仓库
        $repository = UserRepository::make();
        
        // 循环用户
        foreach($users as $user)
        {
            $repository->model($user);
            
            $money = bcmul($this->money, (float) $bi / 100, 2);

            // 发放
            $repository->orderMoneyRemain('red', $money, $content);
            
            // 感恩奖，从关系链中查找
            (new Thank($money, $user->user_all))->run('【' . $user->username . '】感恩奖');
        }
    }
}